package bai3.com.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

import bai3.com.util.Account;

/**
 * @author nglehien
 * Oct 21, 2012 - 8:10:26 PM
 */

public class BankSystem extends UnicastRemoteObject implements
		BankSystemInterface {
	private ArrayList<Account> accounts;
	public static final String BANK_SERVER = "bank_server";
	File data = new File("bai_03/Bank.dat");
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected BankSystem() throws ClassNotFoundException, IOException {
		super();
		accounts = new ArrayList<Account>();
		accounts = getAccountList();
	}

	@Override
	public boolean register(Account account) throws IOException {
		Account temp = get(account.getUsername());
		if (temp == null) {
			FileOutputStream fileOutputStream = new FileOutputStream(data);
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(
					fileOutputStream);
			accounts.add(account);
			objectOutputStream.writeObject(accounts);
			objectOutputStream.close();
			return true;
		}
		return false;
	}

	@Override
	public boolean signIn(Account account) throws RemoteException {
		Account temp = get(account.getUsername());
		if (temp != null) {
			if (temp.getPassword().equals(account.getPassword())) {
				return true;
			}
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ArrayList<Account> getAccountList() throws IOException,
			ClassNotFoundException {
		FileInputStream fileInputStream = new FileInputStream(data);
		ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
		this.accounts = (ArrayList<Account>) inputStream.readObject();
		inputStream.close();
		return accounts;
	}

	private Account get(String username) {
		for (int i = 0; i < accounts.size(); i++) {
			Account account = accounts.get(i);
			if (account.getUsername().equals(username)) {
				return account;
			}
		}
		return null;
	}
}
